import os
import time
import datetime
import subprocess
import sys
import contextlib
from .time import get_adb_format_time

__all__=(
    "adb_log",
    "adb_log_context",
)


'''
    V — Verbose (lowest priority) 
    D — Debug 
    I — Info 
    W — Warning 
    E — Error 
    F — Fatal 
    S — Silent (highest priority, on which nothing is ever printed) 
'''
log_levels = ("V","D","I","W","E","F","S")


def adb_log(since_time: float, log_file_path=None,log_level="I"):
    '''
        打印adb在某一个时间点之后的日志
    '''
    if log_level not in log_level:
        raise AttributeError("无法识别该日志等级，log_level应该在{}中选择".format(log_levels))
    if not isinstance(log_file_path, str):
        return
    t = get_adb_format_time(since_time)
    adb_cmd = "adb -s 127.0.0.1:62001 logcat -v time -t \"{t}\" *:{l}".format(t=t,l=log_level)
    # os.system(adb_cmd)
    exec_cmd(adb_cmd,log_file_path)

@contextlib.contextmanager
def adb_log_context(log_file_path=None,log_level="I"):
    '''
        打印adb日志的上下文管理器
        日志时间范围为: 执行with块中代码的时间段
        with .. as start_time
        其中 start_time 是 with 块中代码开始执行的时间
    '''
    start_time = time.time()
    yield start_time
    adb_log(start_time,log_file_path,log_level)

def exec_cmd(cmd,log_file):
    args = cmd.split()
    with open(log_file,"w",encoding="utf-8") as f:
        p = subprocess.Popen(args, stdout=subprocess.PIPE,stdin=sys.stdin, bufsize=1)
        for line in iter(p.stdout.readline, b''):
            line = line.decode("utf-8").strip()
            f.write(line+"\n")
        p.stdout.close()
        p.wait()

